import React, { useState, useEffect } from 'react';
import {
  Card,
  Space,
  Grid,
  ProgressBar,
  List,
  Image,
  Ellipsis
} from 'antd-mobile';
import './Dashboard.css';
import { useRequest } from 'ahooks';
import { getOrders, getProducts, getUsers } from '../../api/dashboard';
const Dashboard = () => {
  const [statistics, setStatistics] = useState({
    orderCount: 0,
    orderPendingCount: 0,
    orderFinishedCount: 0,
    orderAmount: 0,
    userCount: 0,
    productCount: 0
  });

  const [recentOrders, setRecentOrders] = useState([]);
  const [hotProducts, setHotProducts] = useState([]);
  const [loading, setLoading] = useState(true);

  const { runAsync: fetchOrders } = useRequest(getOrders, {
    manual: true
  });
  const { runAsync: fetchProducts } = useRequest(getProducts, {
    manual: true
  });
  const { runAsync: fetchUsers } = useRequest(getUsers, {
    manual: true
  });

  const userId = JSON.parse(localStorage.getItem('user') || '{}').id;

  const fetchData = async () => {
    setLoading(true);

    const orders = await fetchOrders({params:{id:userId}});
    const users = await fetchUsers({params:{id:userId}});
    const products = await fetchProducts({params:{id:userId}});

    // 计算统计数据
    const orderCount = orders.length;
    const orderPendingCount = orders.filter(order => ['pending', 'paid', 'shipped'].includes(order.status)).length;
    const orderFinishedCount = orders.filter(order => order.status === 'completed').length;
    const orderAmount = orders.reduce((sum, order) => sum + order.totalPrice, 0);
    const userCount = users.length;
    const productCount = products.length;

    setStatistics({
      orderCount,
      orderPendingCount,
      orderFinishedCount,
      orderAmount,
      userCount,
      productCount
    });

    // 获取最近的5个订单
    const sortedOrders = [...orders].sort((a, b) => {
      return new Date(b.createTime) - new Date(a.createTime);
    }).slice(0, 5);

    setRecentOrders(sortedOrders);

    // 获取热门商品（销量最高的前5个）
    const productSales = {};

    // 统计商品销量
    orders.forEach(order => {
      order.orderItems.forEach(item => {
        if (!productSales[item.id]) {
          productSales[item.id] = 0;
        }
        productSales[item.id] += item.quantity;
      });
    });

    // 按销量排序，取前5个
    const hotProductIds = Object.entries(productSales)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 5)
      .map(entry => entry[0]);

    // 获取热门商品详情
    const hotProductsData = products
      .filter(product => hotProductIds.includes(product.id.toString()))
      .sort((a, b) => {
        const aIndex = hotProductIds.indexOf(a.id.toString());
        const bIndex = hotProductIds.indexOf(b.id.toString());
        return aIndex - bIndex;
      })
      .slice(0, 5);

    setHotProducts(hotProductsData);
    setLoading(false);
  }
  // 获取统计数据
  useEffect(() => {
    fetchData();
  }, []);

  // 获取订单状态文本
  const getOrderStatusText = (status) => {
    switch (status) {
      case 'pending':
        return '待付款';
      case 'paid':
        return '待发货';
      case 'shipped':
        return '待收货';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return '未知状态';
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };

  return (
    <div className="dashboard-container">
      <div className="dashboard-header">
        <h2>控制台</h2>
        <p>欢迎使用商城管理系统</p>
      </div>

      {loading ? (
        <div className="loading-container">
          <div className="loading-spinner">加载中...</div>
        </div>
      ) : (
        <>
          {/* 统计卡片 */}
          <div className="stats-cards">
            <Grid columns={3} gap={12}>
              <Grid.Item>
                <Card className="stats-card orders-card">
                  <div className="stats-card-content">
                    <div className="stats-icon">订</div>
                    <div className="stats-info">
                      <div className="stats-title">订单总数</div>
                      <div className="stats-value">{statistics.orderCount}</div>
                    </div>
                  </div>
                  <div className="stats-footer">
                    <div>待处理：{statistics.orderPendingCount}</div>
                    <div>已完成：{statistics.orderFinishedCount}</div>
                  </div>
                </Card>
              </Grid.Item>

              <Grid.Item>
                <Card className="stats-card users-card">
                  <div className="stats-card-content">
                    <div className="stats-icon">用</div>
                    <div className="stats-info">
                      <div className="stats-title">用户总数</div>
                      <div className="stats-value">{statistics.userCount}</div>
                    </div>
                  </div>
                  <div className="stats-footer">
                    <ProgressBar
                      percent={statistics.userCount > 0 ? 100 : 0}
                      style={{ '--track-width': '4px' }}
                    />
                  </div>
                </Card>
              </Grid.Item>

              <Grid.Item>
                <Card className="stats-card products-card">
                  <div className="stats-card-content">
                    <div className="stats-icon">品</div>
                    <div className="stats-info">
                      <div className="stats-title">商品总数</div>
                      <div className="stats-value">{statistics.productCount}</div>
                    </div>
                  </div>
                  <div className="stats-footer">
                    <ProgressBar
                      percent={statistics.productCount > 0 ? 100 : 0}
                      style={{ '--track-width': '4px' }}
                    />
                  </div>
                </Card>
              </Grid.Item>
            </Grid>

            <Card className="revenue-card">
              <div className="revenue-card-content">
                <div className="revenue-title">总收入</div>
                <div className="revenue-value">¥{statistics.orderAmount.toFixed(2)}</div>
              </div>
            </Card>
          </div>

          {/* 最近订单 */}
          <Card className="recent-orders-card" title="最近订单">
            {recentOrders.length === 0 ? (
              <div className="empty-data">暂无订单数据</div>
            ) : (
              <List>
                {recentOrders.map(order => (
                  <List.Item
                    key={order.id}
                    extra={getOrderStatusText(order.status)}
                    description={`订单号: ${order.id} | 时间: ${formatDate(order.createTime)}`}
                  >
                    <div className="order-item-content">
                      <span className="order-item-name">
                        {order.orderItems[0].name}
                        {order.orderItems.length > 1 ? ` 等${order.orderItems.length}件商品` : ''}
                      </span>
                      <span className="order-item-price">¥{order.totalPrice.toFixed(2)}</span>
                    </div>
                  </List.Item>
                ))}
              </List>
            )}
          </Card>

          {/* 热门商品 */}
          <Card className="hot-products-card" title="热门商品">
            {hotProducts.length === 0 ? (
              <div className="empty-data">暂无商品数据</div>
            ) : (
              <List>
                {hotProducts.map(product => (
                  <List.Item
                    key={product.id}
                    prefix={
                      <Image
                        src={product.images[0]}
                        style={{ borderRadius: 4 }}
                        fit='cover'
                        width={40}
                        height={40}
                      />
                    }
                    description={`价格: ¥${product.price.toFixed(2)} | 库存: ${product.stock}`}
                  >
                    <Ellipsis direction='end' rows={1} content={product.name} />
                  </List.Item>
                ))}
              </List>
            )}
          </Card>
        </>
      )}
    </div>
  );
};

export default Dashboard; 